<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-检验报告`"
		width="1200px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		:fullscreen="true"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail'" label-width="200px" :show-message="false">
			<div ref="box1">
				<div class="flex-between-center margin-bottom-4">
					<el-tag type="primary" effect="plain">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<div class="flex-end-center">
						<jk-button v-show="pageType === 'detail'" icon="el-icon-printer" @click="onPrintBtn">打印</jk-button>
					</div>
				</div>
				<jk-card class="margin-bottom-10">
					<el-row>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="单据编号">
								<span class="read-only-2">{{ ruleForm.code || '系统自动生成' }}</span>
							</el-form-item>
						</el-col>

						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="过磅单" prop="weighingRecordCode">
								<span v-if="pageType === 'detail'">{{ ruleForm.weighingRecordCode }}</span>
								<remoteSearchCodeInput
									v-else
									placeholder="过磅单"
									only-key="weighingRecordId"
									query-name="weighingRecordCode"
									:form-data="ruleForm"
									@on-select="onSelectWeighingRecordCodeChange"
								></remoteSearchCodeInput>
							</el-form-item>
						</el-col>
						<!--                        过磅单带出-->
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="到货日期" prop="arrivalDate">
								<span class="read-only-2">{{ ruleForm.arrivalDate }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="原批" prop="primaryBatchCode">
								<span class="read-only-2">{{ ruleForm.primaryBatchCode }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="厂批" prop="workshopBatchCode">
								<span class="read-only-2">{{ ruleForm.workshopBatchCode }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="产地" prop="producerName">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.producerName }}</span>
								<el-input v-else v-model="ruleForm.producerName" size="medium" placeholder="产地" />
							</el-form-item>
						</el-col>
						<!--棉花年度(无字段)-->
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="棉花年度" prop="producerName">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.producerName }}</span>
								<el-date-picker
									v-else
									v-model="ruleForm.producerName"
									type="year"
									placeholder="选择年"
									size="medium"
									format="yyyy"
									value-format="yyyy"
									style="width: 100%"
								>
								</el-date-picker>
							</el-form-item>
						</el-col>
						<!--类型(棉花种类)-->
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="类型" prop="cottonTypeName">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.cottonTypeName }}</span>
								<el-input v-else v-model="ruleForm.cottonTypeName" size="medium" placeholder="类型" />
							</el-form-item>
						</el-col>
						<!--过磅单带出-->
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="件数" prop="count">
								<span class="read-only-2">{{ ruleForm.count }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="供货方" prop="supplyName">
								<span class="read-only-2">{{ ruleForm.supplyName }}</span>
							</el-form-item>
						</el-col>
						<!--运输单位(缺少字段)-->
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="运输单位" prop="count">
								<span class="read-only-2">{{ ruleForm.count }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="毛重" prop="grossWeight">
								<span class="read-only-2">{{ ruleForm.grossWeight }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="净重" prop="netWeight">
								<span class="read-only-2">{{ ruleForm.netWeight }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="皮重" prop="tare">
								<span class="read-only-2">{{ ruleForm.tare }}</span>
							</el-form-item>
						</el-col>
						<!--公定重量（公重）-->
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="公定重量(吨)" prop="commonWeight">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.commonWeight }}</span>
								<el-input v-else v-model="ruleForm.commonWeight" disabled size="medium" placeholder="公定重量" />
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item class="margin-bottom-10" label="单包均重(公斤)" prop="onePackAvg">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.onePackAvg }}</span>
								<el-input v-else v-model="ruleForm.onePackAvg" disabled size="medium" placeholder="单包均重（公斤）" />
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
			</div>
			<jk-divider-card title="检验明细" class="margin-top-30" icon="el-icon-news" :title-style="{ color: '#2d8cf0' }" :style="{ borderColor: '#c8dae7' }">
				<el-row class="flex-start-center-wrap">
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="技术唛头" prop="technicalMarking">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.technicalMarking }}</span>
							<el-input v-else v-model="ruleForm.technicalMarking" type="textarea" autosize size="medium" placeholder="技术唛头" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="长度">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.length }}</span>
							<jk-number-input v-else v-model="ruleForm.length" autosize size="medium" placeholder="长度" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="回潮率" prop="resurgence">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.resurgence }}</span>
							<jk-number-input v-else v-model="ruleForm.resurgence" autosize size="medium" placeholder="长度" @change="calculateWeight" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="含杂率" prop="trashContent">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.trashContent }}</span>
							<jk-number-input v-else v-model="ruleForm.trashContent" autosize size="medium" placeholder="含杂率" @change="calculateWeight" />
						</el-form-item>
					</el-col>
					<!--品级检验（品级）-->
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="品级检验" prop="grade">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.grade }}</span>
							<el-input v-else v-model="ruleForm.grade" type="textarea" autosize size="medium" placeholder="品级检验" />
						</el-form-item>
					</el-col>
					<!--颜色级（无字段）-->
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="颜色级" prop="percentageOfMacron">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.percentageOfMacron }}</span>
							<el-input v-else v-model="ruleForm.percentageOfMacron" type="textarea" autosize size="medium" placeholder="颜色级" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="工制支数" prop="workNumber">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.workNumber }}</span>
							<jk-number-input v-else v-model="ruleForm.workNumber" autosize size="medium" placeholder="工制支数" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="含糖" prop="sugary">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.sugary }}</span>
							<el-input v-else v-model="ruleForm.sugary" type="textarea" autosize size="medium" placeholder="含糖" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="马克隆值" prop="macron">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.macron }}</span>
							<jk-number-input v-else v-model="ruleForm.macron" autosize size="medium" placeholder="马克隆值" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="马克隆百分比" prop="percentageOfMacron">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.percentageOfMacron }}</span>
							<el-input v-else v-model="ruleForm.percentageOfMacron" type="textarea" autosize size="medium" placeholder="马克隆百分比" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="KX730平均长度" prop="avgLength">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.avgLength }}</span>
							<jk-number-input v-else v-model="ruleForm.avgLength" autosize size="medium" placeholder="KX730平均长度" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="KX730整齐度指数" prop="uniformityIndex">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.uniformityIndex }}</span>
							<jk-number-input v-else v-model="ruleForm.uniformityIndex" autosize size="medium" placeholder="KX730整齐度指数" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="公重与净重差异率(%)" prop="differenceRate">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.differenceRate }}</span>
							<el-input v-else v-model="ruleForm.differenceRate" type="textarea" autosize size="medium" placeholder="公重与净重差异率(%)" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="KX730上半部平均长度" prop="upperHalfAvgLength">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.upperHalfAvgLength }}</span>
							<jk-number-input v-else v-model="ruleForm.upperHalfAvgLength" autosize size="medium" placeholder="KX730上半部平均长度" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="KX730短纤维含量(12.7mm)" prop="shortFiberContent">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.shortFiberContent }}</span>
							<jk-number-input v-else v-model="ruleForm.shortFiberContent" autosize size="medium" placeholder="KX730短纤维含量(12.7mm)" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="公检单位" prop="inspectUnitName">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.inspectUnitName }}</span>
							<el-input v-else v-model="ruleForm.inspectUnitName" type="textarea" autosize size="medium" placeholder="公检单位" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="备注" prop="remark">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.remark }}</span>
							<el-input v-else v-model="ruleForm.remark" type="textarea" autosize size="medium" placeholder="备注" />
						</el-form-item>
					</el-col>
				</el-row>
			</jk-divider-card>
			<el-row class="margin-top-10">
				<el-col :span="8">
					<el-form-item class="margin-bottom-10" label="部长">
						<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.ministerName }}</span>
						<remote-search-emp-input
							v-else
							placeholder="部长"
							only-key="minister"
							query-name="ministerName"
							:form-data="ruleForm"
							@on-select="onSelectMinisterChange"
						></remote-search-emp-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item class="margin-bottom-10" label="技术员">
						<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.technicianName }}</span>
						<remote-search-emp-input
							v-else
							placeholder="技术员"
							only-key="technician"
							query-name="technicianName"
							:form-data="ruleForm"
							@on-select="onSelectTechnicianChange"
						></remote-search-emp-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item class="margin-bottom-10" label="检验" prop="inspectorName">
						<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.inspectorName }}</span>
						<remote-search-emp-input
							v-else
							placeholder="检验"
							only-key="inspector"
							query-name="inspectorName"
							:form-data="ruleForm"
							@on-select="onSelectInspectorChange"
						></remote-search-emp-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '../../../../mixins/cal-dialog-height';
    import { spinYarnCountPriceConfigCreate } from '../../../../api/material/yarnCounPrice';
    import remoteSearchProductInput from '../../../technology/order/components/remote-search-product-input';
    import {
        productionCottonInspectCreate,
        productionCottonInspectGet,
        productionCottonInspectUpdate
    } from '../../../../api/material/inspectionReport';
    import { systemBusinessDictPage } from '../../../../api/basicData/businessDict';
    import remoteSearchEmpInput from '@/views/production/order/components/remote-search-emp-input/index.vue';
    import remoteSearchCodeInput from './remote-search-code-input/index.vue';
    export default {
        mixins: [calHeight],
        components: { remoteSearchEmpInput, remoteSearchProductInput, remoteSearchCodeInput },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            copy: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                tableLoading: false,
                ystemBusinessDictList: [],
                saveBtnLoading: false,
                workshopList: [],
                ruleForm: {
                    'arrivalDate': '',
                    'avgLength': 0,
                    'belongDate': '',
                    'commonWeight': 0,
                    'cottonTypeCode': '',
                    'cottonTypeId': 0,
                    'cottonTypeName': '',
                    'count': 0,
                    'differenceRate': 0,
                    'formerQualityLogo': '',
                    'grade': '',
                    'grossWeight': 0,
                    'inspectUnitCode': '',
                    'inspectUnitId': 0,
                    'inspectUnitName': '',
                    'inspector': 0,
                    'inspectorName': '',
                    'length': 0,
                    'macron': 0,
                    'minister': 0,
                    'ministerName': '',
                    'netWeight': 0,
                    'onePackAvg': 0,
                    'onePackTare': 0,
                    'packStr': '',
                    'percentageOfMacron': '',
                    'primaryBatchCode': '',
                    'primaryBatchId': 0,
                    'producerCode': '',
                    'producerId': 0,
                    'producerName': '',
                    'productCode': '',
                    'productId': 0,
                    'productName': '',
                    'remark': '',
                    'resurgence': 0,
                    'shortFiberContent': 0,
                    'sugary': '',
                    'supplyCode': '',
                    'supplyId': 0,
                    'supplyName': '',
                    'tare': 0,
                    'technicalMarking': '',
                    'technician': 0,
                    'technicianName': '',
                    'trashContent': 0,
                    'typeCode': '',
                    'typeId': 0,
                    'typeName': '',
                    'uniformityIndex': 0,
                    'upperHalfAvgLength': 0,
                    'waterImpurityRate': 0,
                    'weighingRecordCode': '',
                    'weighingRecordId': 0,
                    'workNumber': 0,
                    'workshopBatchCode': '',
                    'workshopBatchId': 0
                },
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                rules: {
                    inspectorName: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onSelectWeighingRecordCodeChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'weighingRecordCode', e.arrivedGoodsItemCode); // 过磅单子项code
                    this.$set(this.ruleForm, 'weighingRecordId', e.arrivedGoodsItemId); // 过磅单子项id
                    this.$set(this.ruleForm, 'arrivalDate', e.belongDate); // 过磅单子项belongDate
                    this.$set(this.ruleForm, 'primaryBatchCode', e.primaryBatchCode);
                    this.$set(this.ruleForm, 'workshopBatchCode', e.workshopBatchCode);
                    this.$set(this.ruleForm, 'workshopBatchId', e.workshopBatchId);
                    this.$set(this.ruleForm, 'supplyName', e.supplyName);
                    this.$set(this.ruleForm, 'supplyId', e.supplyId);
                    this.$set(this.ruleForm, 'supplyCode', e.supplyCode);
                }
            },
            onPrintBtn() {
                const routeUrl = this.$router.resolve({
                    name: 'inspectionReport',
                    query: {
                        ids: this.ruleForm.id
                    }
                });
                window.open(routeUrl.href, '_blank');
            },
            onSelectMinisterChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'minister', e.id);
                    this.$set(this.ruleForm, 'ministerName', e.name);
                }
            },
            onSelectTechnicianChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'technician', e.id);
                    this.$set(this.ruleForm, 'technicianName', e.name);
                }
            },
            onSelectInspectorChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'inspector', e.id);
                    this.$set(this.ruleForm, 'inspectorName', e.name);
                }
            },
            /**
             * 计算公重的公式：
             * 锯齿棉：(100-含杂)*108.5/97.5/(100+回潮)*净重
             * 皮辊棉：(100-含杂)*108.5/97/(100+回潮)*净重
             * @param code
             */
            calculateWeight() {
                const newNum = (100 - this.ruleForm.trashContent) * 108.5 / 97.5 / (100 + this.ruleForm.resurgence) * this.ruleForm.netWeight ? (100 - this.ruleForm.trashContent) * 108.5 / 97.5 / (100 + this.ruleForm.resurgence) * this.ruleForm.netWeight : '';
                const commonWeightNum = newNum ? Number(newNum.toFixed(3)) : '';
                this.$set(this.ruleForm, 'commonWeight', commonWeightNum);
                this.getOnePackAvgValue(commonWeightNum);
            },
            getOnePackAvgValue(commonWeightNum) {
                const newNum = commonWeightNum / this.ruleForm.count * 1000;
                const onePackAvg = newNum ? Number(newNum.toFixed(1)) : '';
                this.$set(this.ruleForm, 'onePackAvg', onePackAvg);
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId || this.copy) {
                    params.auditState = 1;
                    delete params.id;
                }
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId || this.copy ? productionCottonInspectCreate : productionCottonInspectUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionCottonInspectGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                        const onePackTare = ((this.ruleForm.grossWeight - this.ruleForm.netWeight) / this.ruleForm.count) * 1000;
                        this.$set(this.ruleForm, 'onePackTare', onePackTare);
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.$nextTick(() => {
                        this.$refs.ruleForm.clearValidate();
                    });
                    this.getDependentData();
                }
            }
        }
    };
</script>
